package com.example.teachmvandroidchart.ui

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.Spinner
import android.widget.Toast
import com.android.frame.mvp.CommonBaseActivity
import com.example.teachmvandroidchart.databinding.ActivitySeriaPortHelperBinding
import com.gyf.immersionbar.ImmersionBar
import android_serialport_api.SerialPortFinder
import com.bjw.bean.ComBean
import com.bjw.utils.FuncUtil
import com.bjw.utils.SerialHelper
import com.chad.library.adapter.base.BaseQuickAdapter
import com.example.teachmvandroidchart.Adapter.AnimationAdapter
import com.example.teachmvandroidchart.Adapter.LogListAdapter
import com.example.teachmvandroidchart.Adapter.SpAdapter
import com.example.teachmvandroidchart.R
import com.example.teachmvandroidchart.util.ByteUtil
import com.example.teachmvandroidchart.util.Status
import java.io.IOException
import java.util.ArrayList
import java.util.HashMap

/**
 * Created by dell on 2021/8/11.
 */
class PortActivity: CommonBaseActivity<ActivitySeriaPortHelperBinding>(){
    private var serialPortFinder: SerialPortFinder? = null
    private var serialHelper: SerialHelper? = null

    private var logListAdapter: LogListAdapter? = null
    private val list = ArrayList<Map<String, Any>>()
    var map: Map<String, Any>? = null

    override fun handleView(savedInstanceState: Bundle?) {
        openSerialPort()

        Handler(Looper.getMainLooper()).postDelayed({
            /**
             * 数据初始化（200毫秒）AddDeviceActivity
             * */
            intView()
        }, 300)

    }
    private fun intView(){



        ImmersionBar.with(this).titleBar(binding.toolbar).keyboardEnable(true).init()
        ImmersionBar.with(this).titleBar(binding.toolbar).init()
        setSupportActionBar(binding.toolbar)
        val actionBar = supportActionBar
        actionBar?.setDisplayHomeAsUpEnabled(true)
        //设置文本不可输入
        binding.EditText1.isEnabled = false
        binding.EditText2.isEnabled = false


    }



    private fun openSerialPort(){
        serialPortFinder = SerialPortFinder()
        serialHelper = object : SerialHelper() {
            override fun onDataReceived(comBean: ComBean) {
                runOnUiThread {
//                    Toast.makeText(
//                        baseContext,
//                        FuncUtil.ByteArrToHex(comBean.bRec),
//                        Toast.LENGTH_SHORT
//                    ).show()
                    /*
                    * TODO 将获取的数据进行列表适配
                    * */
                    map = HashMap()
                    (map as HashMap<String, Any>)["Value"] =comBean.sRecTime + ":   " +
                            ByteUtil.hexStringToString(ByteUtil.bytesToHexString(comBean.bRec))
                    list.add(map as HashMap<String, Any>)
                    Handler(Looper.getMainLooper()).postDelayed({
                        /**
                         * 列表数据的溢处理已经适配
                         * */
                        if (list.size>12){
                            map = list[0]
                            list.remove(map)

                        }
                        initAdapter()
                    }, 300)

                }
            }
        }

        //获取串口地址
        val ports = serialPortFinder!!.allDevicesPath
        //设置波特率地址
        val botes = arrayOf(
            "0",
            "50",
            "75",
            "110",
            "134",
            "150",
            "200",
            "300",
            "600",
            "1200",
            "1800",
            "2400",
            "4800",
            "9600",
            "19200",
            "38400",
            "57600",
            "115200",
            "230400",
            "460800",
            "500000",
            "576000",
            "921600",
            "1000000",
            "1152000",
            "1500000",
            "2000000",
            "2500000",
            "3000000",
            "3500000",
            "4000000"
        )
        val spAdapter = SpAdapter(this)
        /*
         * TODO 适配下拉列表（串口地址）
        * */
        spAdapter.setDatas(ports)
        binding.spSerial.adapter = spAdapter
        binding.spSerial.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View,
                position: Int,
                id: Long
            ) {
                serialHelper?.close()

                serialHelper?.port = ports[position]

                binding.EditText1.setText(ports[position])
                binding.open.text = "关闭串口"

            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
        /*
         * TODO 适配下拉列表（波特率地址）
        * */
        val spAdapter2 = SpAdapter(this)
        spAdapter2.setDatas(botes)
        binding.spBote.adapter = spAdapter2
        binding.spBote.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View,
                position: Int,
                id: Long
            ) {
                serialHelper?.close()
                serialHelper?.setBaudRate(botes[position])
                binding.EditText2.setText(botes[position])
                binding.open.text = "关闭串口"

            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
    }
    override fun initListener() {
        //打开串口
        binding.open.setOnClickListener{
            try {
                serialHelper?.open()
                binding.open.text = "打开成功"
                showToast("打开成功")


            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        //发送消息
        binding.send.setOnClickListener{

            if (binding.radioGroup.getCheckedRadioButtonId() == R.id.radioButton1) {
                if (binding.SendText.text.toString().isNotEmpty()) {
                    if (serialHelper!!.isOpen) {
                        serialHelper!!.sendTxt(binding.SendText.text.toString())
                    } else {
                        showToast("搞毛啊,串口都没打开")
                    }
                } else {
                    showToast("填数据吧")
                }
            } else {
                if (binding.SendText.text.toString().length > 0) {
                    if (serialHelper!!.isOpen) {
                        serialHelper!!.sendHex(binding.SendText.text.toString())
                    } else {
                        showToast("搞毛啊,串口都没打开")
                    }
                } else {
                    showToast("填数据吧")
                }
            }
        }

        //toolbar返回按钮监听
        binding.toolbar.setNavigationOnClickListener { finish() }
    }

    private fun initAdapter() {
        logListAdapter = LogListAdapter(list)
        //打开动画
        logListAdapter?.animationEnable ?: false
        logListAdapter!!.addChildClickViewIds(R.id.textView)
        logListAdapter!!.setOnItemChildClickListener { adapter, view, position ->

            var status = adapter.getItem(position) as Status
            when (view.id) {
                R.id.textView -> showToast(list[position]["Value"].toString())

                else -> {
                }
            }
        }
        //logListAdapter!!.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInRight)
        mRecyclerView?.adapter = logListAdapter



    }

    override fun onDestroy() {

        super.onDestroy()
        serialHelper!!.close()
    }

}